package com.joysuch.wwyt.dzhapi.service.impl;

import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dzhapi.dto.BuildDataDto;
import com.joysuch.wwyt.dzhapi.enums.ApiStaticParameter;
import com.joysuch.wwyt.dzhapi.exception.ApiException;
import com.joysuch.wwyt.dzhapi.service.ApiTokenVerifyService;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: JamesZY
 * @date: 2021/9/7
 * @description:
 */
@Slf4j
@Service
public class ApiTokenVerifyServiceImpl implements ApiTokenVerifyService {
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public BuildDataDto verifyToken(HttpServletRequest request) {
        return this.getToken(request);
    }

    private BuildDataDto getToken(HttpServletRequest request) {
        String token = this.getHeaderToken(request);
        if (Strings.isBlank(token)) {
            log.error("令牌为空");
            throw new ApiException(Status.API_TOKEN_IS_NULL_ERROR);
        }
        String tokenStr = (String) redissonClient.getBucket(ApiStaticParameter.API_TOKEN + ":" + token).get();
        if (StringUtil.isEmpty(tokenStr)) {
            throw new ApiException(Status.API_TOKEN_ERROR);
        }
        String[] split = tokenStr.split("@");
        if (!split[2].equals(token)) {
            log.error("令牌失效");
            throw new ApiException(Status.API_TOKEN_ERROR);
        }
        return this.carryBuildData(split);
    }

    private BuildDataDto carryBuildData(String[] str) {
        BuildDataDto dto = new BuildDataDto();
        if (str.length > 1) {
            dto.setTenentId(Long.valueOf(str[0]));
            dto.setOrgCode(str[1]);
        }
        return dto;
    }

    private String getHeaderToken(HttpServletRequest request) {
        String token = null;
        try {
            token = request.getHeader("token");
        } catch (Exception e) {
            log.error("Header鉴权不是token");
        }
        return token;
    }
}

